/*
 * @Author: xiehangyun 
 * @Date: 2025-05-10 18:19:41 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-03 15:30:26
 */

import { Col, Divider, Price, Row, SearchBar, Tour } from '@nutui/nutui-react-taro';
import { Image, ScrollView, Text, View } from '@tarojs/components';
import Taro, { useDidHide, useDidShow } from "@tarojs/taro";
import clsx from 'clsx'; // 添加 clsx 的导入
import chunk from 'lodash/chunk';
import { autorun, toJS } from "mobx";
import { observer } from "mobx-react-lite";
import { ReactNode, useEffect, useRef, useState } from "react";
import utilsApi from 'src/api/utilsApi';
import MyEmpty from 'src/components/MyEmpty/MyEmpty';
import MyScrollView from 'src/components/MyScrollView/MyScrollView';
import PageLayer from 'src/components/PageLayer/PageLayer';
import goGoodsDetail from 'src/subPages/GoodsDetail/goGoodsDetail';
import utils from 'src/utils/utils';
import utilsStore from 'src/utils/utilsStore';
import { GoodsCategoryData, GoodsData, PriceZoneData } from 'types/type';
import styles from "./category.module.less";
import categoryStore from './categoryStore';
import toDesign from 'src/subPages/Design/designComponent/toDesign';
import { throttle } from 'lodash';

interface Iprops {
    children?: ReactNode
}

// 分类页面
const Category = observer((props: Iprops) => {

    const dom = useRef<HTMLDivElement | null>(null);
    const [showTour, setShowTour] = useState(false);

    const [goodsCategoryDatas, setGoodsCategoryDatas] = useState<Array<GoodsCategoryData>>(categoryStore.goodsCategoryDatas);
    const [activeFirstProductType, setActiveFirstProductType] = useState<undefined | number>(undefined);

    // 价格带数据
    const [priceZoneDatas, setPriceZoneDatas] = useState<Array<{ min: number, max: number }>>([]);
    const [secondProductTypes, setSecondProductTypes] = useState<Array<GoodsCategoryData>>([]);
    const [activeSecondProductType, setActiveSecondProductType] = useState<Array<number>>([]);
    const [goodsList, setGoodsList] = useState<Array<GoodsData>>(toJS(categoryStore.goodsList));
    const [loading, setLoading] = useState(categoryStore.loading);

    useEffect(() => autorun(() => {
        setGoodsCategoryDatas(toJS(categoryStore.goodsCategoryDatas));
        setActiveFirstProductType(categoryStore.activeFirstProductType);
        setSecondProductTypes(toJS(categoryStore.secondProductTypes));
        setActiveSecondProductType(toJS(categoryStore.activeSecondProductType));
        setGoodsList(toJS(categoryStore.goodsList));
        setLoading(categoryStore.loading);
    }, { delay: 30 }), []);

    // const goodsList = new Array(100).fill(0).map((_, i) => {
    //     return {
    //         id: i, name: `商品名称${i}`, price: 6,
    //         img: "//upload-custom.oss-cn-beijing.aliyuncs.com/1000_1000_717899_02a951c7-281b-4387-8754-5665302b1483.png",
    //         tags: ['方便快捷好看', '标签标'],
    //     }
    // })

    useEffect(() => {
        // 模拟获取商品列表
        // setProductList(['商品1', '商品2', '商品3']);
        categoryStore.init();

        utilsApi
            .queryPropertyByTitle("priceZone")
            .then((priceZoneDatas: Array<{ min: number, max: number }>) => {
                setPriceZoneDatas(priceZoneDatas);
            });

    }, []);

    // const sysInfo = Taro.getWindowInfo(); // 替换为 Taro.getWindowInfo
    // const menuButtonInfo = Taro.getMenuButtonBoundingClientRect();
    // const statusBarHeight = sysInfo.statusBarHeight || 0; // 状态栏高度
    // const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2; // 导航栏总高度

    // 计算商品的高度
    // const getGoodsItemHeight = () => {
    //     return 180 + (((210 - 180) / (430 - 375)) * (sysInfo.windowWidth - 375));
    // };

    useDidShow(() => {
        // categoryStore.setActiveFirstProductType();
        setTimeout(() => {
            if (utilsStore.showTour2) {
                utilsStore.setShowTour2(false);
                setShowTour(true);
            }
        }, 1500);
    });

    useDidHide(() => {
        setShowTour(false);
    });

    return (
        <PageLayer
            className={styles.category}
            showBack={categoryStore.isSwitchKua}
            backText={categoryStore.isSwitchKua && "返回设计"}
            onBack={() => {
                if (categoryStore.isSwitchKua) {
                    Taro.navigateTo({ url: "/subPages/Design/Design" });
                }
            }}
        >
            <SearchBar
                placeholder="请输入您想搜索的内容"
                right={
                    <Text
                        onClick={() => {
                            categoryStore.getNextGoodsList(true);
                        }}
                    >搜索</Text>
                }
                onSearch={(value) => {
                    console.log("onSearch", value);
                    categoryStore.getNextGoodsList(true);
                }}
                onChange={(value) => {
                    console.log("onChange", value);
                    categoryStore.setSearchValue(value);
                }}
                className={styles.customSearchBar}
            />

            {/* 布局 */}
            <Row
                style={{
                    height: utilsStore.containerHeight - utils.rpx2px(80),
                    boxSizing: "border-box",
                    overflow: "hidden",
                    position: "relative"
                }}
            >
                <Col span={6} style={{ height: '100%' }}>
                    <View
                        className={styles.categoryList}
                    >
                        <View
                            className={clsx(
                                styles.categoryItem,
                                { [styles.active]: activeFirstProductType === undefined }
                            )}
                            onClick={() => {
                                categoryStore.setActiveFirstProductType();
                            }}
                        >全部</View>
                        {
                            goodsCategoryDatas
                                .filter(item => item.id !== 48)
                                .map((category) => (
                                    <View
                                        key={category.id}
                                        className={clsx(
                                            styles.categoryItem,
                                            { [styles.active]: activeFirstProductType === category.id }
                                        )}
                                        onClick={() => {
                                            categoryStore.setActiveFirstProductType(category.id);
                                        }}
                                    >
                                        {category.typeName}
                                    </View>
                                ))}
                    </View>
                </Col>
                <Col span={18} >
                    <View className={styles.scrollContainer}>
                        {
                            secondProductTypes
                                // .filter(item => (activeFirstProductType !== 48) ? (item.parentId !== 48) : (item.parentId === 48))
                                .filter(item =>
                                    !Boolean(activeFirstProductType)
                                        ?
                                        ((activeFirstProductType !== 48) ? (item.parentId !== 48) : (item.parentId === 48))
                                        :
                                        (item.parentId === activeFirstProductType)
                                )
                                .map((item) => (
                                    <View
                                        key={item.id}
                                        className={clsx(styles.item, activeSecondProductType.includes(item.id) && styles.active)}
                                        onClick={() => {
                                            categoryStore.setActiveSecondProductType(item.id);
                                        }}
                                    >
                                        <Image
                                            src={utils.ossSuffix(item.typeIcon, 40)}
                                            className={styles.itemImage}
                                        />
                                        <Text className={styles.itemText}>{item.typeName || "--"}</Text>
                                    </View>
                                ))}
                    </View>

                    {
                        priceZoneDatas.length > 0 &&
                        <View className={styles.scrollFilter}>
                            {priceZoneDatas.map((priceZoneData: PriceZoneData, i) => {
                                const active = categoryStore.priceZones.some(item => item.min === priceZoneData.min && item.max === priceZoneData.max);
                                return (
                                    <Text
                                        key={priceZoneData.min}
                                        className={clsx(styles.item, active && styles.active)}
                                        onClick={() => {
                                            categoryStore.seelctPriceZone(priceZoneData);
                                        }}
                                    >
                                        ¥{priceZoneData.min}-¥{priceZoneData.max}
                                    </Text>
                                )
                            })}
                        </View>
                    }

                    {/* 商品列表 */}
                    <ScrollView
                        id="goodsList"
                        className={styles.goodsList}
                        scrollY={true}         // 关键：启用垂直滚动
                        scrollWithAnimation    // 可选：启用滚动动画
                        showScrollbar={false}
                        style={{
                            height: utilsStore.containerHeight - (priceZoneDatas.length > 0 ? utils.rpx2px(350) : utils.rpx2px(270))
                        }}
                        onScroll={throttle(async (e: any) => {
                            const scrollTop = e.target.scrollTop;
                            const scrollHeight = e.target.scrollHeight;
                            const height = utilsStore.containerHeight - (priceZoneDatas.length > 0 ? utils.rpx2px(350) : utils.rpx2px(270))
                            if ((scrollHeight - height - scrollTop) < 200) {
                                categoryStore.getNextGoodsList();
                            }
                        }, 30)}
                    >
                        {
                            !loading && goodsList.length === 0 &&
                            <MyEmpty
                                description="敬请期待..."
                                style={{
                                    paddingTop: '12vh',
                                }}
                            />
                        }
                        {
                            chunk(goodsList, 2).map((goodss: Array<GoodsData>, i) => {
                                // 每两个商品为一组
                                return (
                                    <Row key={i}>
                                        {
                                            goodss.map((goods, ii) => {
                                                return (
                                                    <Col span={12} key={ii} >
                                                        <View
                                                            className={styles.goodsItem}
                                                            onClick={() => {
                                                                goGoodsDetail(goods.productId);
                                                            }}
                                                        >
                                                            <View
                                                                className={styles.goodsImage}
                                                                style={{
                                                                    backgroundImage: `url(${goods.ifShowBorder && utils.ossSuffix(goods.borderImageUrl)}),url(${utils.ossSuffix(goods.productShowImageUrl, 512)})`
                                                                }}
                                                            />
                                                            <Text className={styles.goodsName}>{goods.productName}</Text>
                                                            <View className={styles.goodsFooter}>
                                                                <Price
                                                                    price={goods.pagePrice}
                                                                    size="normal"
                                                                    digits={1}
                                                                />
                                                                <Text className={styles.originalPrice}>{`¥${goods.underlinePrice}`}</Text>
                                                            </View>
                                                        </View>
                                                    </Col>
                                                );
                                            })
                                        }
                                    </Row>
                                );
                            })
                        }
                        <Divider
                            style={{
                                borderStyle: 'solid',
                                width: '50%',
                                margin: '0rpx auto',
                                padding: '30rpx 0',
                            }}
                        >
                            到底了
                        </Divider>
                    </ScrollView>

                </Col>
            </Row >

            <Tour
                className="nut-custom-tour"
                visible={showTour && !categoryStore.loading}
                onClose={() => {
                    utilsStore.setShowTour2(false);
                    setShowTour(false);
                }}
                list={[
                    {
                        content: '2.再选择一个你喜欢的商品',
                        target: 'goodsList',
                    }
                ]}
                location="top-start"
                offset={[0, 0]}
                maskWidth={utilsStore.windowWidth * 0.75}
                maskHeight={utilsStore.containerHeight - (priceZoneDatas.length > 0 ? utils.rpx2px(350) : utils.rpx2px(270))}
            />

        </PageLayer >
    );
});

export default Category;


